import qs from 'qs';
import axios from 'axios'
import store from '@/store'
import router from '@/router/index'
import { AlertModule, ToastPlugin } from 'vux'
import { getToken, removeToken } from '@/utils/auth'
import Vue from 'vue'
Vue.use(ToastPlugin)
// 创建axios实例
const axiosService = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 50000,                  // 请求超时时间
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})


// request拦截器
axiosService.interceptors.request.use(config => {
  if (store.getters.token) {
    console.log(getToken())
    config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if(config.method  === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded' ){
    console.log("-----------------------------------------")
    config.data = qs.stringify(config.data, {allowDots: true});
    console.log("---------------------===--------------------")
  }
  console.log(config.method  === 'post')
  console.log(config.headers['Content-Type'] === 'application/x-www-form-urlencoded')
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
axiosService.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.statusCode !== 200) {
      AlertModule.show({content: res.message})
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err:' + error.response.status)// for debug
    if (error.response.status === 401) {
      removeToken()
      AlertModule.show({title: '提示',content: '您的登录已过期，请重新登录！'})
      router.push({ path: '/login' })
    }else{

    }
    return Promise.reject(error)
  }
)

export default axiosService
